import request from '@/utils/http'

// 后端字典项返回结构（与后端 DictItemResponse 对齐）
export interface DictItemResponse {
  id: number
  dict_key: string
  dict_value: string
  dict_type: string
  category?: string | null
  score?: number
  options?: string
  sort_order?: number
  create_time?: string
  update_time?: string
  [key: string]: any
}

// 批量缓存返回结构：按类型分组
export type DictCacheResponse = Record<string, DictItemResponse[]>

// 列表分页响应（字典类型）
export interface DictTypeResponse {
  id?: number
  type_code: string
  type_name: string
  type_desc?: string | null
  created_at?: string
  updated_at?: string
}

export interface DictTypeListResponse {
  total: number
  items: DictTypeResponse[]
  page: number
  size: number
  pages: number
}

// 创建/更新请求参数
export interface DictTypeCreate {
  type_code: string
  type_name: string
  type_desc?: string | null
}

export interface DictTypeUpdate {
  type_code?: string
  type_name?: string
  type_desc?: string | null
}

// 查询参数（与后端 DictTypeQuery 对齐）
export interface DictTypeQuery {
  current?: number // 后端别名 current -> page
  size?: number
  type_code?: string
  type_name?: string
  keyword?: string
}

/**
 * 获取字典类型分页列表
 */
export function fetchDictTypeList(params: DictTypeQuery) {
  return request.post<DictTypeListResponse>({
    url: '/system/dicts/list',
    params
  })
}

/**
 * 创建字典类型
 */
export function createDictType(params: DictTypeCreate) {
  return request.post<DictTypeResponse>({
    url: '/system/dicts/create',
    params,
    showSuccessMessage: true
  })
}

/**
 * 更新字典类型
 */
export function updateDictType(typeId: number, params: DictTypeUpdate) {
  return request.put<DictTypeResponse>({
    url: `/system/dicts/${typeId}`,
    params,
    showSuccessMessage: true
  })
}

/**
 * 删除字典类型
 */
export function deleteDictType(typeId: number) {
  return request.del<{ message: string }>({
    url: `/system/dicts/${typeId}`,
    showSuccessMessage: true
  })
}

/**
 * 批量获取字典缓存
 * @param types 可选的字典类型编码数组；不传或空数组返回全部
 */
export function fetchDictCache(types?: string[]) {
  return request.post<DictCacheResponse>({
    url: '/system/dicts/cache',
    params: types && types.length ? { types } : {}
  })
}



